package com.timmy.ble;

import android.os.Bundle;
import android.os.Environment;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;

import com.inuker.bluetooth.library.Code;
import com.inuker.bluetooth.library.utils.ByteUtils;
import com.timmy.ble.callback.BleCallbackImpl;
import com.timmy.ble.dfu.DfuService;

import java.io.File;
import java.util.UUID;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import no.nordicsemi.android.dfu.DfuProgressListener;
import no.nordicsemi.android.dfu.DfuServiceInitiator;
import no.nordicsemi.android.dfu.DfuServiceListenerHelper;

public class InfoActivity extends AppCompatActivity {

    private static final String TAG = InfoActivity.class.getSimpleName();
    @BindView(R.id.tv_proge)
    TextView mTvProge;
    private BleManager mBleManager;
    private byte[] value = new byte[20];

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_info);
        ButterKnife.bind(this);
        mBleManager = BleManager.getInstance(this);

        mBleManager.openNotify(new BleCallbackImpl() {
            @Override
            public void onResponse(int code) {
                super.onResponse(code);
                Log.i(TAG, "onResponse: " + code);
            }

            @Override
            public void onNotify(UUID service, UUID character, byte[] value) {
                super.onNotify(service, character, value);
                Log.i(TAG, "onNotify: " + ByteUtils.byteToString(value));
            }
        });

        mBleManager.registerConnectStatusListener(null);
    }

    @Override
    protected void onResume() {
        DfuServiceListenerHelper.registerProgressListener(this, mDfuProgressListener);
        super.onResume();
    }

    @Override
    protected void onPause() {
        DfuServiceListenerHelper.unregisterProgressListener(this, mDfuProgressListener);
        super.onPause();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        mBleManager.disconnect();
    }


    // 和校验
    public byte sumCheck(byte[] data) {
        int sum = 0;
        for (int i = 0; i < data.length; i++) {
            int d = data[i] & 0x0FF;
            sum += d;
        }

        return (byte) (0xff & sum);
    }

    private DfuProgressListener mDfuProgressListener = new DfuProgressListener() {
        @Override
        public void onDeviceConnecting(String deviceAddress) {
            Log.i(TAG, "onDeviceConnecting");
        }

        @Override
        public void onDeviceConnected(String deviceAddress) {
            Log.i(TAG, "onDeviceConnected");
        }

        @Override
        public void onDfuProcessStarting(String deviceAddress) {
            mTvProge.setText("升级准备中....");
        }

        @Override
        public void onDfuProcessStarted(String deviceAddress) {
            mTvProge.setText("升级准备好了,马上开始升级....");
        }

        @Override
        public void onEnablingDfuMode(String deviceAddress) {
            Log.i(TAG, "onEnablingDfuMode");
        }

        @Override
        public void onProgressChanged(String deviceAddress, int percent, float speed, float avgSpeed, int currentPart, int partsTotal) {
            //Log.i(TAG, "percent:" + percent + " speed：" + speed + " avgSpeed：" + avgSpeed + " currentPart：" + currentPart + " partsTotal：" + partsTotal);

            mTvProge.setText("升级进度：" + percent + " %");
        }

        @Override
        public void onFirmwareValidating(String deviceAddress) {
            Log.i(TAG, "onFirmwareValidating");
        }

        @Override
        public void onDeviceDisconnecting(String deviceAddress) {
            Log.i(TAG, "onDeviceDisconnecting");
        }

        @Override
        public void onDeviceDisconnected(String deviceAddress) {
            Log.i(TAG, "onDeviceDisconnected");
        }

        @Override
        public void onDfuCompleted(String deviceAddress) {
            mTvProge.setText("升级成功");
        }

        @Override
        public void onDfuAborted(String deviceAddress) {
            mTvProge.setText("升级流产，失败");
        }

        @Override
        public void onError(String deviceAddress, int error, int errorType, String message) {
            mTvProge.setText("升级失败");

        }
    };

    @OnClick({R.id.btn_dfu, R.id.btnstart_dfu, R.id.disconne})
    public void onViewClicked(View view) {
        switch (view.getId()) {


            case R.id.btn_dfu:

                // 进入dfu升级模式
                value[0] = (byte) 0xA9;
                value[1] = (byte) 0x05;
                value[19] = sumCheck(value);

                mBleManager.write(value, new BleCallbackImpl() {
                    @Override
                    public void onResponse(int code) {
                        super.onResponse(code);

                        if (code == Code.REQUEST_SUCCESS) {
                            Log.i(TAG, "写入成功");
                        } else if (code == Code.REQUEST_FAILED) {
                            Log.i(TAG, "写入失败");
                        }
                    }
                });

                break;
            case R.id.btnstart_dfu:

                String sdcard = Environment.getExternalStorageDirectory().toString() + "/testfile.zip";

                if (new File(sdcard).exists()) {
//                if (true) {
                    new DfuServiceInitiator(mBleManager.getMac())
                            .setDisableNotification(true)
                        .setZip(R.raw.testfile)
//                            .setZip(sdcard)
                            .start((getBaseContext()), DfuService.class);
                } else {
                    Toast.makeText(this, "升级文件找不到", Toast.LENGTH_SHORT).show();
                }
                break;
            case R.id.disconne:
                mBleManager.disconnect();
                break;
        }
    }


}
